<template>
    <div ref="lineChart" class="echarts"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, watch, onMounted, onUnmounted, nextTick } from 'vue-demi'
let myEchart = null
const lineChart = ref(null)
const props = defineProps({
  data: {
    type: Object,
    default: () => {}
  }
})
const option = ref({
  color: [
    '#5B8FF9',
    '#5AD8A6',
    '#5D7092',
    '#F6BD16',

  ],
   tooltip: {
      trigger: 'axis',
      axisPointer: {
         type: 'shadow'
      },
      textStyle: {
         color: "rgba(255, 255, 255, 1)"
      },
      backgroundColor: "rgba(0, 0, 0, 0.8)",
      borderColor: "rgba(219, 230, 255, 0.8)"
   },
   legend: {
      data: [],
      x: "right",
      textStyle: {
         color: "#8C8C8C",
         fontSize: 12
      },
      //设置字体颜色
      
      top: 10,
      //right: 50,
      itemWidth: 20,
      itemHeight: 10,
      itemGap: 15
   },
   grid: {
      left: '3%',
      right: '3%',
      bottom: '2%',
      containLabel: true
   },
   xAxis: [{
      type: "category",
      axisLabel: {
         color: "#9ca1a1",
         fontSize: 12,
         //字体Roboto
          fontFamily: "Roboto"

      },
      data: [],
      axisLine: {
         lineStyle: {
            color: "#9ca1a1"
         }
      }
   }],
   yAxis: [{
      type: "value",
      axisLabel: {
         color: "#8C8C8C",
         fontSize: 12
      },
      axisTick: {
         show: false
      },
      axisLine: {
         show: false,
         lineStyle: {
            color: "white"
         }
      },
      nameTextStyle: {
         color: "#A9AEB2",
         fontSize: "12"
      },
      splitLine: {
         show: true,
         lineStyle: {
            color: [
               "#ddd"
            ],
            width: 1,
            type: "solid"
         }
      }
   }],
   series: []
})

onMounted(() => {
  initPage()

})

//监听props.data的变化
watch(() => props.data.seriesData, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    initPage()
  }
},
{
  deep: true
}
)


const initPage = ()=>{

  const xAxisData = props.data.xAxisData

  let data = props.data.seriesData

  option.value.xAxis[0].data = xAxisData
  option.value.series = data
  //legend
  option.value.legend.data = data.map(item => item.name)
  

  myEchart = echarts.init(lineChart.value)
  myEchart.setOption(option.value)

  window.addEventListener('resize', () => {
    myEchart.resize()
  })
}

onUnmounted(() => {
  echarts.dispose(myEchart)
  window.removeEventListener('resize', () => {
    myEchart.resize()
  })
})
</script>

<style scoped lang="scss">
  .echarts {
    width: 100%;
    height: 230px;
  }
</style>
